package com.xcity.game.buff.effect;

import java.util.List;

import com.xcity.db.entity.Build;
import com.xcity.db.entity.Player;
import com.xcity.game.buff.Buff;
import com.xcity.game.buff.BuffEffector;
import com.xcity.game.build.BuildLevelUpTemplate;
import com.xcity.game.common.PlayerPool;
import com.xcity.game.worldevent.WorldEventBuffTemplateWrap;
import com.xcity.game.worldevent.WorldEventTemplate;
import com.xcity.pomelo.push.SyncPush;
import com.xcity.pomelo.push.sync.MapSync;

/**
 * 世界事件buff效果
 * @author YangLi
 *
 */
public class WorldEventBuffEffect implements BuffEffector {

	@Override
	public boolean effect(Buff buff, Player player) {
		WorldEventBuffTemplateWrap template = (WorldEventBuffTemplateWrap) buff.getTemplate();
		WorldEventTemplate ref = template.getRef();
		float factor = ref.getType() == WorldEventTemplate.GOOD ? (100f + ref.getEffect()) / 100 : (100f - ref.getEffect()) / 100;
		player.poolSet(PlayerPool.PROPERTY_BUILD_INCOME_FACTOR_PREFIX + ref.getIndustry(), factor);
		List<Build> buildings = player.getBuildings().getBuildings();
		for (int i = buildings.size() - 1; i >= 0; i--) {
			Build b = buildings.get(i);
			if (b.getTemplate().getGroup() == ref.getIndustry()) {
				b.setTempMoney(b.settle(buff.getCreateTime(), true)); // 结算该buff生效之前的收益
//				if (ref.getType() == WorldEventTemplate.GOOD) {
//					b.setAdjustRate(b.getAdjustRate() * (100 + ref.getEffect()) / 100);
//				} else {
//					b.setAdjustRate(b.getAdjustRate() * (100 - ref.getEffect()) / 100);
//				}
				if (player.isOnline()) {
//					BuildLevelUpTemplate temp = b.getTemplate().getLevelUpTemplate(b.getLevel());
//					int added = (int) (temp.getIncome() * factor - temp.getIncome());
					int income = b.getIncomePerMinute();
					int added = (int) (income * factor - income);
					player.send(new MapSync(SyncPush.SYNC_BUILD_INCOME_ADDED, b.getId(), added));
				}
			}
		}
		if (player.getPool().getLongValue(PlayerPool.PROPERTY_LAST_WORLD_EVENT_END_TIME) < buff.getEndTime()) {
			player.poolSet(PlayerPool.PROPERTY_LAST_WORLD_EVENT_END_TIME, buff.getEndTime());
		}
		return true;
	}
	
	@Override
	public boolean uneffect(Buff buff, Player player) {
		WorldEventBuffTemplateWrap template = (WorldEventBuffTemplateWrap) buff.getTemplate();
		WorldEventTemplate ref = template.getRef();
		List<Build> buildings = player.getBuildings().getBuildings();
		for (int i = buildings.size() - 1; i >= 0; i--) {
			Build b = buildings.get(i);
			if (b.getTemplate().getGroup() == ref.getIndustry()) {
				b.setTempMoney(b.settle(buff.getEndTime(), true)); // 结算该buff截止时间之前的收益
//				b.setAdjustRate(1.0f);
				if (player.isOnline()) {
					player.send(new MapSync(SyncPush.SYNC_BUILD_INCOME_ADDED, b.getId(), 0));
				}
			}
		}
		player.poolRemove(PlayerPool.PROPERTY_BUILD_INCOME_FACTOR_PREFIX + ref.getIndustry());
		return true;
	}

}
